<template>
  <div>
    <CustomDialog
        :title="state.dialog.title"
        v-model:visible="state.dialog.isShowDialog"
        dialogWidth="500px"
        @close="closeDialog"
        :showSubmit="true"
        :dialogFooterBtn="true"
    >
      <el-form ref="dialogFormRef" :rules="rules" :model="state.ruleForm" size="default" label-width="90px">
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="state.ruleForm.newPassword"/>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="state.ruleForm.confirmPassword" type="password"/>
        </el-form-item>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(dialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
    </CustomDialog>
  </div>
</template>

<script setup lang="ts">
import {reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {useLoginApi} from '/@/api/login';
import msg from '/@/utils/messageUtils';

const dialogFormRef = ref();
const state = reactive({
  ruleForm: {
    newPassword: '',
    confirmPassword: '',
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '确认',
  },
});

const rules = reactive<FormRules>({
  newPassword: [{required: true, message: '请输入新密码', trigger: 'blur'}],
  confirmPassword: [{required: true, message: '请输入确认密码', trigger: 'blur'}],
});
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};

const openDialog = () => {
  state.dialog.isShowDialog = true;
};

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      try {
        await useLoginApi().updatePwd(state.ruleForm);
        msg().success('操作成功');
        closeDialog();
      } catch (error) {
        msg().error(error);
      }
    }
  });
};

defineExpose({openDialog});
</script>

<style scoped lang="scss"></style>
